package com.yx.frame.http;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.json.JSONArray;
import com.yx.frame.authority.AuthorityManager;
import com.yx.frame.authority.User;
import com.yx.frame.log.LogFactory;
import com.yx.frame.log.LogWriter;
import com.yx.frame.server.Application;
import com.yx.frame.service.ServiceError;
import com.yx.frame.service.ServiceResult;

/**
 * @ClassName: UploadHandleServlet
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @author: shiyanbo
 * @date: 2016-05-23 下午19:25:50
 *
 */
public class HttpFileUploadServletJre6 extends HttpServlet {
	private static final long serialVersionUID = -41885787517587174L;
	protected static LogWriter log = LogFactory.getInstance().getLogWriter();
	static final String CONTENT_TYPE = "text/html; charset=utf-8";

	public HttpFileUploadServletJre6() {

	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		/*
		if(AsyncServiceExecutor.isAllright()){
			AsyncContext aCtx = request.startAsync();
			AsyncServiceExecutor.execute(new AsyncHandler(aCtx));
		}else{
			handler(request,response);
		}
		*/
		handler(request,response);
	}
	
	/*
	public final class AsyncHandler implements Runnable {
		AsyncContext asyncContext;
		public AsyncHandler(AsyncContext asyncContext) {
			this.asyncContext = asyncContext;
		}

		public void run() {
			handler((HttpServletRequest) asyncContext.getRequest(), (HttpServletResponse) asyncContext.getResponse());
			asyncContext.complete();
		}
	}
	*/
	
	public static final void handler(HttpServletRequest request, HttpServletResponse response) {
		long t = System.currentTimeMillis();
		ServiceError error = new ServiceError();
		User user = null;
		Map<String, String> map = new HashMap<String, String>();
		try {
			request.setCharacterEncoding("UTF-8");
			response.setCharacterEncoding("UTF-8");
//			user = getCurrentUser(request, error);
			//if (error.isError())
				//return;
			ServiceResult returnJSON = new ServiceResult();
			JSONArray fileUrls = new JSONArray();
			/*
			Collection<Part> parts = request.getParts();
			for (Iterator<Part> iterator = parts.iterator(); iterator.hasNext();) {
				Part part = iterator.next();
				String fileName = getFileName(part);
				if (fileName != null && !"".equals(fileName)) {
					long length = part.getSize();
					InputStream input = part.getInputStream();
					String storageName = Application.getProvider().writeFile(fileName, input, length);
					fileUrls.put(storageName);
				}
			}
			*/
			//获得磁盘文件条目工厂  
	        DiskFileItemFactory factory = new DiskFileItemFactory();  
	        //获取文件需要上传到的路径  
	        String path = request.getSession().getServletContext().getRealPath("/tmp");
	        factory.setRepository(new File(path));
	        factory.setSizeThreshold(1024*1024*10);
	        ServletFileUpload upload = new ServletFileUpload(factory);  
	        List<FileItem> list = (List<FileItem>) upload.parseRequest(request);
	        
	        for (FileItem item : list) {
				String name = item.getFieldName();
				if (item.isFormField()) {
					String value = item.getString();
					map.put(name, value);
					//request.setAttribute(name, value);
				} else {
					String value = item.getName();
					int start = value.lastIndexOf("\\");
					String fileName = value.substring(start + 1);
					//request.setAttribute(name, fileName);
					/*
					OutputStream out = new FileOutputStream(new File(path, filename));
					InputStream in = item.getInputStream();
					int length = 0;
					byte[] buf = new byte[1024];
					System.out.println("获取上传文件的总共的容量：" + item.getSize());
					while ((length = in.read(buf)) != -1) {
						out.write(buf, 0, length);
					}
					in.close();
					out.close();
					*/
					if (fileName != null && !"".equals(fileName)) {
						long length = item.getSize();
						InputStream input = item.getInputStream();
						String storageName = "";
						storageName = Application.getProvider().writeFile(fileName, input, length);
						fileUrls.put(storageName);
					}
				}
			}
	        returnJSON.put("FileUrl", fileUrls);
	        writeResponse(response, returnJSON);
		} catch (Exception e) {
			error.setErrorMessage(e.getMessage());
		} finally {
			if (error.isError()) {
				//error(user, "FileUpload", "返回JSON:" + error);
				//writeResponse(response, error);
			}
			debug(user, "FileUpload", "耗时：" + (System.currentTimeMillis() - t) + "毫秒！");
		}
	}
	
	private static final User getCurrentUser(HttpServletRequest request, ServiceError error) throws Exception {
		String uId = null;
		try {
			uId = request.getParameter("UId");			
		} catch (Exception e) {
			error.setErrorMessage("非法的用户认证信息");
			return null;
		}
		return AuthorityManager.getInstance().authentication(uId, error);
	}
	
	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		writeResponse(response, new ServiceError("不支持GET请求"));
	}
	
	/*
	private static String getFileName(Part part) {
		// 获取header信息中的content-disposition，如果为文件，则可以从其中提取出文件名
		String cotentDesc = part.getHeader("content-disposition");
		String fileName = null;
		Pattern pattern = Pattern.compile(fileNameExtractorRegex);
		Matcher matcher = pattern.matcher(cotentDesc);
		if (matcher.find()) {
			fileName = matcher.group();
			fileName = fileName.substring(10, fileName.length() - 1);
		}
		return fileName;
	}
	*/
	
	private static void writeResponse(HttpServletResponse response, ServiceResult serviceResult) {
		try {
			response.setContentType(CONTENT_TYPE);
			// response.setContentType("<meta http-equiv=\"Access-Control-Allow-Origin\" content=\"*\">");
			response.setHeader("Access-Control-Allow-Origin", "*");
			PrintWriter out = response.getWriter();
			if (serviceResult == null) {
				serviceResult = new ServiceError("返回为空");
			}
//			String strResponse = "<script type='text' id='json'>" + serviceResult.toString()
//					+ "</script><script type='text/javascript'>window.name=document.getElementById('json').innerHTML;</script>";
			out.println(serviceResult);
			out.flush();
		} catch (Exception e) {
		}

		// out.close();
	}

	public static void error(User user, String serviceName, String logMsg) {
		log.error(user, serviceName, logMsg);
	}

	public static void debug(User user, String serviceName, String logMsg) {
		log.debug(user, serviceName, logMsg);
	}
}